<template>
	<div class="room-details-container">
		<!-- 页面头部 -->
		<div class="header-section">
			<div class="header-left">
				<el-button icon="el-icon-back" @click="goBack" class="back-button">返回</el-button>
				<h2 class="room-title">{{ address }}</h2>
			</div>
			<div class="header-actions">
				<el-tooltip content="刷新数据" placement="top">
					<el-button type="primary" icon="el-icon-refresh" @click="getsmartLokList" class="refresh-button" circle></el-button>
				</el-tooltip>
			</div>
		</div>

		<!-- 主要内容区域 -->
		<div class="main-content">
			<!-- 左侧统计卡片和标签页切换 -->
			<div class="left-panel">
				<!-- 统计卡片 -->
				<div class="stats-grid">
					<div class="stat-card blue" @click="activateTab('locks')">
						<div class="stat-icon"><i class="el-icon-lock"></i></div>
						<div class="stat-details">
							<span class="stat-title">智能锁</span>
							<span class="stat-value">{{ smartlocksList.length || 0 }}</span>
						</div>
						<div class="stat-refresh" @click.stop="refreshLocks">
							<i class="el-icon-refresh"></i>
						</div>
					</div>
					<div class="stat-card green" @click="activateTab('tenant')">
						<div class="stat-icon"><i class="el-icon-user"></i></div>
						<div class="stat-details">
							<span class="stat-title">人员</span>
							<span class="stat-value">{{ tenantsCount || 0 }}</span>
						</div>
						<div class="stat-refresh" @click.stop="refreshTenants">
							<i class="el-icon-refresh"></i>
						</div>
					</div>
					<div class="stat-card orange" @click="activateTab('keys')">
						<div class="stat-icon"><i class="el-icon-key"></i></div>
						<div class="stat-details">
							<span class="stat-title">钥匙</span>
							<span class="stat-value">{{ keysCount || 0 }}</span>
						</div>
						<div class="stat-refresh" @click.stop="refreshKeys">
							<i class="el-icon-refresh"></i>
						</div>
					</div>
					<div class="stat-card purple" @click="activateTab('logs')">
						<div class="stat-icon"><i class="el-icon-time"></i></div>
						<div class="stat-details">
							<span class="stat-title">开门记录</span>
							<span class="stat-value">{{ openLogsCount || 0 }}</span>
						</div>
						<div class="stat-refresh" @click.stop="refreshLogs">
							<i class="el-icon-refresh"></i>
						</div>
					</div>
				</div>

				<!-- 自定义标签导航 -->
				<div class="custom-tabs">
					<div
						v-for="tab in tabs"
						:key="tab.name"
						:class="['tab-item', activeTab === tab.name ? 'active' : '']"
						@click="activateTab(tab.name)"
					>
						<i :class="tab.icon"></i>
						<span>{{ tab.label }}</span>
					</div>
				</div>
			</div>

			<!-- 右侧内容展示 -->
			<div class="right-panel">
				<div class="content-container" v-loading="loading">
					<div v-show="activeTab === 'locks'" class="tab-content-panel">
						<smartlocks ref="smartlocks"></smartlocks>
					</div>
					<div v-show="activeTab === 'tenant'" class="tab-content-panel">
						<div class="panel-title">
							人员

						</div>
						<user ref="tenantIndex" :homeId="roomId" :hideUI="true" @update-count="updateTenantsCount"></user>
					</div>
					<div v-show="activeTab === 'keys'" class="tab-content-panel">
						<div class="panel-title">
							钥匙
						</div>
						<tenantkey-index ref="tenantkeyIndex" :homeId="roomId" :hideUI="true" @update-count="updateKeysCount"></tenantkey-index>
					</div>
					<div v-show="activeTab === 'logs'" class="tab-content-panel">
						<div class="panel-title">开门记录</div>
						<openLogs ref="openLogs" @update-count="updateOpenLogsCount"></openLogs>
					</div>
				</div>
			</div>
		</div>


	</div>
</template>

<script>
	import {
		listHome
	} from "@/api/lock/home";
	import { clearAllPasswords, delKeyClearCard } from "@/api/lock/tenantkey";
	import { getQrCode } from "@/api/lock/tenantUser";
	import smartlocks from "./smartlocks";
	import openLogs from "./openLogs";
	import tenantkeyIndex from "@/views/lock/tenantkey/index";
	import user from "@/views/lock/room/user/index";
	export default {
		name: "RoomDetails",
		dicts: ['can_use', 'version'],
		components: {
			smartlocks,
			openLogs,
			tenantkeyIndex,
			user
		},
		data() {
			return {
				address: "",
				smartlocksList: [],
				roomId: null,
				sId: null,
				tenantsCount: 0,
				keysCount: 0,
				openLogsCount: 0,
				loading: false,
				activeTab: 'locks',
				tabs: [
					{ name: 'locks', label: '智能锁', icon: 'el-icon-lock' },
					{ name: 'tenant', label: '人员', icon: 'el-icon-user' },
					{ name: 'keys', label: '钥匙', icon: 'el-icon-key' },
					{ name: 'logs', label: '开门记录', icon: 'el-icon-time' }
				],
				// 二维码相关数据
				qrCodeDialog: false,
				qrCodeUrl: null,
			};
		},
		mounted() {
			this.roomId = this.$route.query.id;
			this.loading = true;
			this.getsmartLokList();

			// 预加载所有子组件数据
			this.preloadAllComponentData();
		},
		methods: {
			goBack() {
				this.$router.back()
			},
			// 确认清除密码
			confirmClearPassword() {
				this.$confirm('确认清除该房间所有智能锁的密码吗？此操作不可逆，密码将被永久删除。', '警告', {
					confirmButtonText: '确认清除',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.execClearAllPasswords();
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消清除操作'
					});
				});
			},
			// 确认清除卡片
			confirmClearCard() {
				this.$confirm('确认清除该房间所有智能锁的卡片吗？此操作不可逆，卡片将被永久删除。', '警告', {
					confirmButtonText: '确认清除',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.execClearCard();
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消清除卡片操作'
					});
				});
			},
			// 清除所有密码
			execClearAllPasswords() {
				this.loading = true;

				if (!this.roomId) {
					this.$message.error('未找到房间ID');
					this.loading = false;
					return;
				}

				if (!this.smartlocksList || this.smartlocksList.length === 0) {
					this.$message.error('未找到设备信息');
					this.loading = false;
					return;
				}

				// 获取第一个智能锁的MAC地址
				const mac = this.smartlocksList[0].mac;
				if (!mac) {
					this.$message.error('未找到设备MAC地址');
					this.loading = false;
					return;
				}

				// 调用清除密码接口，使用正确的API方法和参数
				clearAllPasswords(mac).then(res => {
					if (res.code === 200) {
						this.$message.success('密码清除任务已下发，请等待设备处理');
						// 刷新钥匙列表
						setTimeout(() => {
							this.refreshKeys();
						}, 1000);
					} else {
						this.$message.error(res.msg || '清除密码失败');
					}
					this.loading = false;
				}).catch(err => {
					console.error('清除密码请求失败:', err);
					this.$message.error('清除密码请求失败');
					this.loading = false;
				});
			},
			// 执行清除卡片
			execClearCard() {
				this.loading = true;

				if (!this.roomId) {
					this.$message.error('未找到房间ID');
					this.loading = false;
					return;
				}

				if (!this.smartlocksList || this.smartlocksList.length === 0) {
					this.$message.error('未找到设备信息');
					this.loading = false;
					return;
				}

				// 获取第一个智能锁的MAC地址
				const mac = this.smartlocksList[0].mac;
				if (!mac) {
					this.$message.error('未找到设备MAC地址');
					this.loading = false;
					return;
				}

				// 调用清除卡片接口
				delKeyClearCard(mac).then(res => {
					if (res.code === 200) {
						this.$message.success('卡片清除任务已下发，请等待设备处理');
						// 刷新钥匙列表
						setTimeout(() => {
							this.refreshKeys();
						}, 1000);
					} else {
						this.$message.error(res.msg || '清除卡片失败');
					}
					this.loading = false;
				}).catch(err => {
					console.error('清除卡片请求失败:', err);
					this.$message.error('清除卡片请求失败');
					this.loading = false;
				});
			},
			activateTab(tabName) {
				this.activeTab = tabName;

				// 根据激活的标签页重新加载相应数据
				switch(tabName) {
					case 'locks':
						this.refreshLocks();
						break;
					case 'tenant':
						this.refreshTenants();
						break;
					case 'keys':
						this.refreshKeys();
						break;
					case 'logs':
						this.refreshLogs();
						break;
				}
			},
			getsmartLokList() {
				console.log('开始加载智能锁列表，roomId:', this.roomId);
				this.loading = true;
				let info = {};
				info.id = this.roomId
				listHome(info).then(response => {
					console.log('智能锁列表加载成功:', response);
					this.smartlocksList = response.rows;
					let list = this.smartlocksList[0];
					if (list) {
						this.address = list.cellName + "/" + list.unitName + "/" + list.floorName + "/" + list.roomName;
					}
					this.loading = false;
					console.log('智能锁列表加载完成，loading状态已关闭');

					// Actualizar datos de componentes hijo
					this.$nextTick(() => {
						// Actualizar todas las tablas según la pestaña activa
						this.updateComponentBasedOnActiveTab();
						// Actualizar todos los contadores
						this.updateAllCounts();
					});
				}).catch((error) => {
					console.error('智能锁列表加载失败:', error);
					this.loading = false;
				});
			},
			// Método para actualizar el componente activo actual
			updateComponentBasedOnActiveTab() {
				// Primero actualizar el componente de la pestaña activa
				switch(this.activeTab) {
					case 'locks':
						if (this.$refs.smartlocks && typeof this.$refs.smartlocks.getList === 'function') {
							this.$refs.smartlocks.getList();
						}
						break;
					case 'tenant':
						if (this.$refs.user && typeof this.$refs.user.getList === 'function') {
							this.$refs.user.getList();
						}
						break;
					case 'keys':
						if (this.$refs.tenantkeyIndex && typeof this.$refs.tenantkeyIndex.getList === 'function') {
							this.$refs.tenantkeyIndex.getList();
						}
						break;
					case 'logs':
						if (this.$refs.openLogs && typeof this.$refs.openLogs.getList === 'function') {
							this.$refs.openLogs.getList();
						}
						break;
				}
			},
			// 刷新智能锁数据
			refreshLocks() {
				this.getsmartLokList();
				// 刷新智能锁组件数据
				if (this.$refs.smartlocks && typeof this.$refs.smartlocks.getList === 'function') {
					this.$refs.smartlocks.getList();
				}
			},
			// 刷新人员数据
			refreshTenants() {
				if (this.$refs.tenantIndex && typeof this.$refs.tenantIndex.getList === 'function') {
					this.$refs.tenantIndex.getList();
					// 延迟更新计数，确保数据加载完成
					setTimeout(() => {
						this.updateTenantsCountFromComponent();
					}, 500);
				}
			},
			// 刷新钥匙数据
			refreshKeys() {
				if (this.$refs.tenantkeyIndex && typeof this.$refs.tenantkeyIndex.getList === 'function') {
					this.$refs.tenantkeyIndex.getList();
					// 延迟更新计数，确保数据加载完成
					setTimeout(() => {
						this.updateKeysCountFromComponent();
					}, 500);
				}
			},
			// 刷新日志数据
			refreshLogs() {
				if (this.$refs.openLogs && typeof this.$refs.openLogs.getList === 'function') {
					this.$refs.openLogs.getList();
					// 延迟更新计数，确保数据加载完成
					setTimeout(() => {
						this.updateOpenLogsCountFromComponent();
					}, 500);
				}
			},
			preloadAllComponentData() {
				console.log('开始预加载所有组件数据...');
				// 设置延时，确保所有组件都完成初始化
				setTimeout(() => {
					// 确保即使是隐藏的标签页内容也加载数据
					if (this.$refs.tenantIndex) {
						// 检查是否有自定义的加载方法，如果有则调用它
						if (typeof this.$refs.tenantIndex.getList === 'function') {
							this.$refs.tenantIndex.getList();
						}
					}

					if (this.$refs.tenantkeyIndex) {
						if (typeof this.$refs.tenantkeyIndex.getList === 'function') {
							this.$refs.tenantkeyIndex.getList();
						}
					}

					if (this.$refs.openLogs) {
						if (typeof this.$refs.openLogs.getList === 'function') {
							this.$refs.openLogs.getList();
						}
					}

					// 设置一个稍长的延迟，等待子组件全部加载完数据后再更新统计
					setTimeout(() => {
						this.updateAllCounts();
						// 确保loading状态被关闭
						this.loading = false;
						console.log('预加载完成，loading状态已关闭');
					}, 1000);
				}, 500);
			},
			updateAllCounts() {
				console.log("正在更新所有计数...");
				this.updateTenantsCountFromComponent();
				this.updateKeysCountFromComponent();
				this.updateOpenLogsCountFromComponent();
			},
			updateTenantsCountFromComponent() {
				// 尝试多种可能的属性名称来获取数量
				if (this.$refs.tenantIndex) {
					if (this.$refs.tenantIndex.total !== undefined) {
						this.tenantsCount = this.$refs.tenantIndex.total;
					} else if (this.$refs.tenantIndex.list && this.$refs.tenantIndex.list.length !== undefined) {
						this.tenantsCount = this.$refs.tenantIndex.list.length;
					} else if (typeof this.$refs.tenantIndex.getTotal === 'function') {
						this.tenantsCount = this.$refs.tenantIndex.getTotal();
					}
					console.log("人员数量更新为:", this.tenantsCount);
				}
			},
			updateKeysCountFromComponent() {
				if (this.$refs.tenantkeyIndex) {
					if (this.$refs.tenantkeyIndex.total !== undefined) {
						this.keysCount = this.$refs.tenantkeyIndex.total;
					} else if (this.$refs.tenantkeyIndex.list && this.$refs.tenantkeyIndex.list.length !== undefined) {
						this.keysCount = this.$refs.tenantkeyIndex.list.length;
					} else if (typeof this.$refs.tenantkeyIndex.getTotal === 'function') {
						this.keysCount = this.$refs.tenantkeyIndex.getTotal();
					}
					console.log("钥匙数量更新为:", this.keysCount);
				}
			},
			updateOpenLogsCountFromComponent() {
				if (this.$refs.openLogs) {
					if (this.$refs.openLogs.total !== undefined) {
						this.openLogsCount = this.$refs.openLogs.total;
					} else if (this.$refs.openLogs.list && this.$refs.openLogs.list.length !== undefined) {
						this.openLogsCount = this.$refs.openLogs.list.length;
					} else if (typeof this.$refs.openLogs.getTotal === 'function') {
						this.openLogsCount = this.$refs.openLogs.getTotal();
					}
					console.log("开门记录数量更新为:", this.openLogsCount);
				}
			},
			updateTenantsCount(count) {
				this.tenantsCount = count;
			},
			updateKeysCount(count) {
				this.keysCount = count;
			},
			updateOpenLogsCount(count) {
				this.openLogsCount = count;
			},
			/** 处理二维码入住按钮操作 */
			handleQrCode() {
				this.qrCodeDialog = true;
				getQrCode(this.roomId).then(response => {
					if (response.code === 200) {
						this.qrCodeUrl = response.msg;
					} else {
						this.$message.error(response.msg || '获取二维码失败');
					}
				}).catch(error => {
					console.error('获取二维码失败:', error);
					this.$message.error('获取二维码失败');
				}).finally(() => {
				});
			},
		},
		watch: {
			activeTab(newVal) {
				this.$nextTick(() => {
					if (newVal === 'tenant') {
						this.updateTenantsCountFromComponent();
					} else if (newVal === 'keys') {
						this.updateKeysCountFromComponent();
					} else if (newVal === 'logs') {
						this.updateOpenLogsCountFromComponent();
					}
				});
			}
		}
	};
</script>

<style scoped lang="scss">
	.room-details-container {
		padding: 10px;
		background-color: #f8f9fa;
		height: calc(100vh - 84px);
		display: flex;
		flex-direction: column;
	}

	/* 头部样式 */
	.header-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24px;
		padding: 16px 20px;
		border-radius: 8px;
		background-color: white;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);

		.header-left {
			display: flex;
			align-items: center;

			.back-button {
				margin-right: 16px;
				color: #409eff;
				border: 1px solid #dcdfe6;
				background-color: white;
				transition: all 0.2s ease;

				&:hover {
					color: #66b1ff;
					border-color: #c6e2ff;
					background-color: #f0f7ff;
				}
			}

			.room-title {
				margin: 0;
				font-size: 18px;
				font-weight: 600;
				color: #303133;
			}
		}

		.header-actions {
			.refresh-button {
				transition: all 0.2s ease;

				&:hover {
					transform: rotate(30deg);
				}
			}
		}
	}

	/* 主内容区域样式 */
	.main-content {
		display: flex;
		flex: 1;
		gap: 20px;
		overflow: hidden;
	}

	/* 左侧面板 */
	.left-panel {
		width: 280px;
		display: flex;
		flex-direction: column;
		gap: 20px;
	}

	/* 统计卡片网格 */
	.stats-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 16px;
	}

	/* 统计卡片样式 */
	.stat-card {
		position: relative;
		padding: 20px;
		border-radius: 8px;
		color: white;
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		transition: all 0.3s ease;
		cursor: pointer;

		&:hover {
			transform: translateY(-5px);
			box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
		}

		&.blue {
			background: linear-gradient(135deg, #1890ff, #096dd9);
		}

		&.green {
			background: linear-gradient(135deg, #52c41a, #389e0d);
		}

		&.orange {
			background: linear-gradient(135deg, #fa8c16, #d46b08);
		}

		&.purple {
			background: linear-gradient(135deg, #722ed1, #531dab);
		}

		.stat-refresh {
			position: absolute;
			top: 10px;
			right: 10px;
			width: 24px;
			height: 24px;
			border-radius: 50%;
			background: rgba(255, 255, 255, 0.2);
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 14px;
			opacity: 0.7;
			transition: all 0.2s ease;

			&:hover {
				opacity: 1;
				transform: rotate(30deg);
				background: rgba(255, 255, 255, 0.3);
			}
		}

		.stat-icon {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 50px;
			height: 50px;
			border-radius: 50%;
			background: rgba(255, 255, 255, 0.2);
			font-size: 24px;
			margin-bottom: 12px;
		}

		.stat-details {
			display: flex;
			flex-direction: column;
			width: 100%;

			.stat-value {
				font-size: 24px;
				font-weight: 700;
				line-height: 1.2;
				margin-top: 6px;
			}

			.stat-title {
				font-size: 14px;
				opacity: 0.9;
			}
		}
	}

	/* 自定义标签导航 */
	.custom-tabs {
		background: white;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

		.tab-item {
			display: flex;
			align-items: center;
			padding: 16px;
			cursor: pointer;
			transition: all 0.2s ease;
			border-left: 3px solid transparent;

			i {
				margin-right: 10px;
				font-size: 18px;
				color: #909399;
			}

			span {
				color: #606266;
			}

			&:hover {
				background-color: #f5f7fa;
			}

			&.active {
				background-color: #f0f5ff;
				border-left-color: #409eff;

				i, span {
					color: #409eff;
					font-weight: 500;
				}
			}
		}
	}

	/* 右侧内容展示区域 */
	.right-panel {
		flex: 1;
		background: white;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
	}

	.content-container {
		height: 100%;
		padding: 20px;
	}

	.tab-content-panel {
		height: 100%;
	}

	.panel-title {
		font-size: 18px;
		font-weight: 600;
		margin-bottom: 16px;
		color: #303133;
		padding-bottom: 12px;
		border-bottom: 1px solid #ebeef5;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	/* 移动端适配 */
	@media (max-width: 991px) {
		.main-content {
			flex-direction: column;
		}

		.left-panel {
			width: 100%;
		}

		.stats-grid {
			grid-template-columns: repeat(4, 1fr);
		}

		.custom-tabs {
			display: flex;
			overflow-x: auto;

			.tab-item {
				border-left: none;
				border-bottom: 3px solid transparent;

				&.active {
					border-left-color: transparent;
					border-bottom-color: #409eff;
				}
			}
		}
	}

	@media (max-width: 768px) {
		.stats-grid {
			grid-template-columns: repeat(2, 1fr);
		}

		.custom-tabs {
			.tab-item {
				padding: 12px;

				i {
					margin-right: 6px;
				}
			}
		}
	}
</style>


